package com.example.module_main.ui.main
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import com.azhon.appupdate.manager.DownloadManager
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.Router
import com.example.lib_common.base.BaseActivity
import com.example.lib_storage.mmkv.AppMMKV
import com.example.module_main.R
import com.example.module_main.databinding.ActivityMainBinding
import com.example.module_main.dialog.AppUpdateDialog
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author yaotianxue
 * @description
 * @date 2025/5/26
 *
 * 1.fragment切换
 * 2.判断版本是否需要更新
 * 3.全局事件总线监听
 *  （1）登陆
 *  （2）退出登陆
 */
@Route(path = Router.Ui.MainActivity)
@AndroidEntryPoint
class MainActivity: BaseActivity<MainViewModel, ActivityMainBinding>(){
    override val mLayoutResId: Int
        get() = R.layout.activity_main

    private lateinit var mMotoCircleFragment: Fragment
    private lateinit var mMotoClubFragment: Fragment
    private lateinit var mMallFragment: Fragment
    private lateinit var mMineFragment: Fragment
    private lateinit var mMessageFragment: Fragment

    companion object {
        private const val MY_CAR_FRAGMENT = "myCar"
        private const val MOTOR_CIRCLE_FRAGMENT = "friends"
        private const val MOTOR_CLUB_FRAGMENT = "club"
        private const val MOTOR_CLUB_FRAGMENT_CHECKING = "club_checking"
        private const val MOTOR_CLUB_FRAGMENT_NOT_JOINED = "club_not_joined"
        private const val MINE_FRAGMENT = "mine"
        private const val MALL_FRAGMENT = "mall"
        private const val MESSAGE_FRAGMENT = "message"

        const val MESSAGE_REGISTRATION_ID = "com.jczy.cyclone.MESSAGE_REGISTRATION_ID"
    }
    //第一次注册获取到registrationID 为null
    private val mRegistrationIDReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(p0: Context?, p1: Intent?) {
                if (MESSAGE_REGISTRATION_ID == p1?.action) {
                    val registrationID = JPushInterface.getRegistrationID(this@MainActivity)
                    Log.d("xxx", "mRegistrationIDReceiver 获取到 registrationID $registrationID")
//                    if (AuthMMKV.hasLogin())
//                        mViewModel.bindJPushRegId(registrationID)
                }
            }
        }
    }
    /*注册广播*/
    private fun registerMessageReceiver() {
        val filter = IntentFilter()
        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        filter.addAction(MESSAGE_REGISTRATION_ID)
        registerReceiver(mRegistrationIDReceiver, filter)
    }

    /**
     * 解除注册广播
     */
    private fun unregisterMessageReceiver() {
        unregisterReceiver(mRegistrationIDReceiver)
    }



    private val mViewModel:MainViewModel by viewModels()


    override fun initData() {
        //版本更新
        mViewModel.checkUpdate()
        //注册极光id广播
        registerMessageReceiver()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterMessageReceiver() //解注册广播,防止内存泄漏
    }

    override fun initView() {
        mMotoClubFragment = ARouter.getInstance().build(Router.Ui.ClubFragment).navigation() as Fragment
        mMotoCircleFragment = ARouter.getInstance().build(Router.Ui.MotorCircleFragment).navigation() as Fragment
        mMallFragment = ARouter.getInstance().build(Router.Ui.MallFragment).navigation() as Fragment
        mMessageFragment = ARouter.getInstance().build(Router.Ui.MessageFragment).navigation() as Fragment
        mMineFragment = ARouter.getInstance().build(Router.Ui.MineFragment).navigation() as Fragment
        navToFragment(R.id.nav_motor_circle)
        mBinding.navMotorCircle.isChecked = true

    }

    override fun initListener() {
        //登陆成功事件总线
//        mViewModel.loginLiveData_.observe(this){
//            if (it){
        //注册极光id
        val registrationID = JPushInterface.getRegistrationID(this)
        Log.d("xxx", "MainActivity 获取到 registrationID $registrationID")
//                mViewModel.bindJPushRegId(registrationID)
//            }
//        }
        //版本更新
        mViewModel.appUpdateLiveData_.observe(this){updateModel->
            if (updateModel != null){
                if (updateModel.latestVersion.isEmpty()
                    || updateModel.downloadUrl.isNullOrEmpty()
                    || updateModel.latestVersion == "1.0.0" //BuildConfig.VERSION_NAME
                ) {
                    return@observe
                }
            }
            val new = updateModel.latestVersion.split(".")
            if (new.isEmpty() || new.size != 3) return@observe
            val current = "1.0.0".split(".")
            val needUpdate = isNeedUpdate(new, current)
            if (!needUpdate) return@observe
            if (updateModel.forceUpGrade != 2 || System.currentTimeMillis() - AppMMKV.lastLaunchTime > 10 * 60 * 1000L) {
                AppUpdateDialog(
                    title = String.format("最新版本%s升级说明", updateModel.latestVersion),
                    message = updateModel.message,
                    updateModel.forceUpGrade != 1//1是强制更新，2是非强制更新
                ) {
                    forceUpdate(updateModel!!.downloadUrl!!, updateModel.latestVersion)
                }.show(supportFragmentManager)
                AppMMKV.lastLaunchTime = System.currentTimeMillis()
            }

        }
        //点击切换fragment
        mBinding.rgBottom.setOnCheckedChangeListener { _, i ->
            navToFragment(i)
        }

    }
    /**
     * 下载app并安装
     */
    private fun forceUpdate(downloadUrl: String, latestVersion: String) {
        val manager = DownloadManager.Builder(this).run {
            apkUrl(downloadUrl)
            apkName("app_new_version.apk")
            enableLog(false)
            smallIcon(R.mipmap.app_icon)
            showBgdToast(true)
            showNotification(true)
            apkVersionName(latestVersion)
            build()
        }
        manager.download()
    }

    private fun navToFragment(id:Int){
        val bt = supportFragmentManager.beginTransaction()
        hideCurrentFragment(bt)
        when(id){
            R.id.nav_motor_club -> {
                if (supportFragmentManager.findFragmentByTag(MOTOR_CLUB_FRAGMENT_NOT_JOINED)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMotoClubFragment, MOTOR_CLUB_FRAGMENT_NOT_JOINED)
                } else {
                    bt.show(mMotoClubFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }
            R.id.nav_motor_circle -> {
                if (supportFragmentManager.findFragmentByTag(MOTOR_CIRCLE_FRAGMENT)?.isAdded == true){
                    bt.show(mMotoCircleFragment)
                }else{
                    bt.add(R.id.fragment_container, mMotoCircleFragment, MOTOR_CIRCLE_FRAGMENT) //tag标记
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }

            R.id.nav_message -> {
                if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMessageFragment, MESSAGE_FRAGMENT)
                } else {
                    bt.show(mMessageFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }
            R.id.nav_motor_mall -> {
                if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMallFragment, MALL_FRAGMENT)
                } else {
                    bt.show(mMallFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }
            R.id.nav_mine -> {
                if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMineFragment, MINE_FRAGMENT)
                } else {
                    bt.show(mMineFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }
        }


    }

    /**
     * 获得未读消息红点更新显示
     */
    private fun updateUnreadMessage(){

    }

    private fun hideCurrentFragment(bt: FragmentTransaction) {
        if (supportFragmentManager.findFragmentByTag(MOTOR_CIRCLE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMotoCircleFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MOTOR_CLUB_FRAGMENT_NOT_JOINED)?.isVisible == true) {
            bt.hide(mMotoClubFragment)
        }

        if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isVisible == true) {
            bt.hide(mMallFragment)
        }

        if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMessageFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMineFragment)
        }
    }

    /**
     * 判断是否需要更新
     */
    private fun isNeedUpdate(new: List<String>, current: List<String>): Boolean {
        if (new[0].toInt() > current[0].toInt()) {
            return true
        } else if (new[0].toInt() < current[0].toInt()) {
            return false
        }
        if (new[1].toInt() > current[1].toInt()) {
            return true
        } else if (new[1].toInt() < current[1].toInt()) {
            return false
        }
        if (new[2].toInt() > current[2].toInt()) {
            return true
        } else if (new[2].toInt() < current[2].toInt()) {
            return false
        }
        return false
    }

}